<?php

namespace App\Http\Controllers\Api;

use App\Models\SysConfig;
use App\Utils\CodeUtil;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class SysConfigController extends Controller
{
    public function index(){
        $list = SysConfig::get()->toArray();
        return view('Api/sys_config/index',["list"=>$list]);
    }


    public function create(){
        return view('Api/sys_config/create');
    }


    /**
     * 保存新建的资源
     */
    function save(Request $request)
    {
        //if ($data['varname'] == '')    return response()->json(['code'=> CodeUtil::API_ERROR,"msg"=> "请输入完整的变量名!"]);
        //$result = SysConfig::where("varname",$request->input("varname"))->first();
        //if(!empty($result))      return response()->json(['code'=> CodeUtil::API_ERROR,"msg"=> "该变量已存在!"]);
        //SysConfig::insert($data);
        $input = $request->input();
        $obj = new SysConfig();
        if(!empty($input["id"])) $obj = SysConfig::find($input["id"]);
        foreach($input as $key => $val) {
            if($key == "file")  continue;
            if($key == 'file_one') {
                if(empty($val)) return response()->json(['code'=> CodeUtil::API_ERROR,"msg"=> "请上传图片!"]);;
                $obj->value = $val;
                continue;
            }
            if($key == 'video') {
                if(empty($val)) return response()->json(['code'=> CodeUtil::API_ERROR,"msg"=> "请上传图片!"]);;
                $obj->value = $val;
                continue;
            }
            $obj->$key = $val;
        }
        $obj->save();
        return response()->json(['code'=> CodeUtil::SUCCESS,"msg"=> "增加成功!"]);
    }

    /**
     * 保存更新的资源
     */
    function update(Request $request)
    {

        $id = $request->input("id");
        $data = $request->input();
        unset($data["id"]);
        $result = SysConfig::where("varname",$request->input("varname"))->where("id","!=",$id)->first();
        if(!empty($result))      return response()->json(['code'=> CodeUtil::API_ERROR,"msg"=> "该变量已存在!"]);
        SysConfig::where("id",$id)->update($data);
        return response()->json(['code'=> CodeUtil::SUCCESS,"msg"=> "保存成功!"]);
    }

    /**
     * 删除指定资源
     */
    function delete(Request $request)
    {
        $id = $request->input("id");
        if (!is_array($id)) $id = [$id];
        SysConfig::whereIn("id",$id)->delete();
        return response()->json(['code'=> CodeUtil::SUCCESS,"msg"=> "删除成功!"]);
    }


    public function imgCreate(Request $request){
        $id = $request->input("id");
        return view('Api/sys_config/create_img',["id"=>$id]);

    }
    public function videoCreate(Request $request){
        $id = $request->input("id");
        return view('Api/sys_config/create_video',["id"=>$id]);
    }


}
